#!/bin/bash

# blog-admin 完整构建和部署脚本（一步到位）
# 使用方法：在 Jenkins 中执行此脚本

# 设置工作目录
WORKSPACE="/var/jenkins_home/workspace/blog-server"
PROJECT_DIR="${WORKSPACE}/blog-admin"
BUILD_DIR="${PROJECT_DIR}/dist"

echo "========================================"
echo "blog-admin 构建和部署"
echo "========================================"
echo "工作目录: $WORKSPACE"
echo "项目目录: $PROJECT_DIR"
echo ""

# 进入项目目录
cd "$PROJECT_DIR" || exit 1

# 1. 安装依赖
echo "步骤1: 安装依赖..."
npm install || {
    echo "依赖安装失败"
    exit 1
}

# 2. 构建项目
echo "步骤2: 构建项目..."
npm run build || {
    echo "构建失败"
    exit 1
}

# 3. 检查构建结果
if [ ! -d "$BUILD_DIR" ] || [ -z "$(ls -A $BUILD_DIR)" ]; then
    echo "错误: 构建目录为空或不存在"
    exit 1
fi

echo "构建成功: $BUILD_DIR"

# 4. 部署项目
echo "步骤3: 部署项目..."
chmod +x "${PROJECT_DIR}/docker-start.sh"
"${PROJECT_DIR}/docker-start.sh" || {
    echo "部署失败"
    exit 1
}

echo "========================================"
echo "构建和部署完成！"
echo "========================================"

